package com.gitee.apanlh.util.tree;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Empty;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.reflection.ReflectionUtils;
import com.gitee.apanlh.util.valid.ValidParam;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 	设置树节点及节点值
 *
 * 	@author Pan
 */
public class TreeProperties {

	/**
	 * 	构造函数
	 *
	 * 	@author Pan
	 */
	private TreeProperties() {
		//	不允许外部实例
		super();
	}

	/**
	 * 	设置树属性
	 *
	 * 	@author Pan
	 * 	@param	<T>				数据类型
	 * 	@param  t				对象
	 * 	@param 	listDynamicTree	动态树集合
	 * 	@return	DynamicTree
	 */
	public static <T> Map<String, Object> setTreeValue(T t, List<Map<String, Object>> listDynamicTree) {
		Map<String, Object> dynamicTree = MapUtils.newLinkedHashMap();

		Field[] fields = ReflectionUtils.getFields(t);
		for (int i = 0, len = fields.length; i < len; i++) {
			Field field = fields[i];
			dynamicTree.put(TreeScan.getAlias(field), ReflectionUtils.getFieldValue(t, field.getName()));
		}

		listDynamicTree.add(dynamicTree);
		return dynamicTree;
	}

	/**
	 * 	设置树子集属性
	 *
	 * 	@author Pan
	 * 	@param	<T>	数据类型
	 * 	@param 	listChildren	子集集合
	 * 	@param 	dynamicTree		父类树
	 * 	@return	List
	 */
	public static <T> List<Map<String, Object>> setTreeChildrenValue(List<T> listChildren, Map<String, Object> dynamicTree) {
		if (ValidParam.isEmpty(listChildren)) {
			return Empty.list();
		}

		List<Map<String, Object>> listChildrenTree = CollUtils.newArrayList();
		Field[] fields = ReflectionUtils.getFields(listChildren);

		IteratorUtils.array(listChildren, t -> {
			Map<String, Object> children = MapUtils.newLinkedHashMap();

			for (int i = 0, len = fields.length; i < len; i++) {
				Field field = fields[i];
				children.put(TreeScan.getAlias(field), ReflectionUtils.getFieldValue(t, field.getName()));
			}
			listChildrenTree.add(children);
		});

		dynamicTree.put(TreeConstant.CHILDREN_TREE_NAME, listChildrenTree);
		return listChildrenTree;
	}

	/**
	 * 	根据注解返回值
	 *
	 * 	@author Pan
	 * 	@param	<T>			数据类型
	 * 	@param 	t			对象
	 * 	@param 	list		字段集合
	 * 	@param 	annotation	注解
	 * 	@return	Object
	 */
	public static <T> Object getIdValueByAnnotation(T t, List<Field> list, Class<? extends Annotation> annotation) {
		for (Field field : list) {
			Annotation scanAnnotationValue = ReflectionUtils.getFieldAnnotation(field, annotation);
			if (scanAnnotationValue != null && field.getDeclaredAnnotation(annotation) == scanAnnotationValue) {
				return ReflectionUtils.getFieldValue(t, field.getName());
			}
		}
		return null;
	}
}
